import { Input, InputRef, NavBar, TextArea, TextAreaRef } from 'antd-mobile'

import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import { RootState } from '@/types/store'
import { useEffect, useRef, useState } from 'react'
type Props = {
  hideInput: () => void
  onUpdate: (key: string, value: string) => void
  type: string
}

const EditInput = ({ hideInput, type, onUpdate }: Props) => {
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  const name = type === 'name' ? '昵称' : '简介'
  const { profile } = useSelector((state: RootState) => state.profile)
  const [value, setValue] = useState(
    type === 'name' ? profile.name : profile.intro
  )
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span className="commit-btn" onClick={() => onUpdate(type, value)}>
            提交
          </span>
        }
        onBack={hideInput}
      >
        编辑{name}
      </NavBar>

      <div className="edit-input-content">
        <h3>{name}</h3>
        {type === 'name' ? (
          <div className="input-wrap">
            <Input
              ref={inputRef}
              placeholder="请输入"
              value={value}
              onChange={(value) => setValue(value)}
            />
          </div>
        ) : (
          <TextArea
            ref={textRef}
            className="textarea"
            showCount
            value={value}
            maxLength={100}
            placeholder="请输入简介"
            onChange={(value) => setValue(value)}
          ></TextArea>
        )}
      </div>
    </div>
  )
}

export default EditInput
